import Vue from "vue"
import VueRouter from "vue-router"
import routes from './routes'
Vue.use(VueRouter)
import store from '@/store'
import { Message } from 'element-ui';
import setting from '@/setting';
import { authToken, menusFormat } from '@/utils/auth'
import menuData from '@/menu.json'
import RoutesData from '@/routes.json'
// 引入页面顶部进度条插件
import NProgress from 'nprogress'
// 进度条配置
NProgress.configure({ minimum: 0.8, easing: 'ease', speed: 300, showSpinner: false })

//路由白名单
const whiteList = ['/login', '/404']

//路由实例
const router = new VueRouter({
    // mode: 'history',
    routes,
    scrollBehavior (to, from, savedPosition) {
        return { x: 0, y: 0 }
    }
})
//https://blog.csdn.net/qq_36437172/article/details/108269846
const VueRouterPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push (to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

const load = (path) => {
    return () => import(`../views/${path}.vue`)
}
const loadDocs = (path) => {
    return () => import(`../components/${path}.vue`)
}
const loadRoutes = (arr, parent = []) => {
    let groups = []
    arr.forEach(route => {
        let group = {
            path: route.path,
            name: route.name,
            meta: {
                title: route.title,
                parent,
                ...route.meta
            },
            component: load(route.component)
        }
        if (route.redirect) group.redirect = route.redirect

        if (route.children) {
            if (route.type === 'layout') {
                group.children = loadRoutes(route.children, [...parent, route])
            } else {
                groups = [...groups, ...loadRoutes(route.children, [...parent, route])]
            }
        }
        groups.push(group)
    })
    return groups
}
//创建路由
export const createRoutes = (arr) => {
    const groups = loadRoutes(arr)

    return [
        {
            path: '/',
            component: loadDocs('layout/index'),
            redirect: '/home',
            children: [
                ...groups,
                {
                    path: '/layout/404',
                    meta: {
                        title: '404'
                    },
                    component: load('404/index'),
                }, {
                    path: '/',
                    redirect: '/home'
                }, {
                    path: '/*',
                    redirect: '/layout/404'
                }
            ]
        }
    ]
}
//将创建好的路由加入路由实例
export const addRoutes = (data) => {
    router.addRoutes(createRoutes(data))
}

addRoutes(RoutesData)

router.beforeEach((to, from, next) => {
    NProgress.start()
    document.title = (to.meta && to.meta.title) ? `${to.meta.title}-${setting.docTitle}` : setting.docTitle
    //是否在白名单里
    if (whiteList.indexOf(to.path) !== -1) {
        next()
    } else {
        if (authToken.hasToken()) {
            //是否设置菜单
            if (store.state.menus.menus) {
                next()
            } else {
                // next()
                const data = menusFormat(menuData)
                store.dispatch('setMenus', data)
                .then(() => {
                    next({ ...to, replace: true })
                })
                .catch(() => {
                    NProgress.done()
                    next(new Error('路由加载错误'))
                })
            }
        } else {
            if (to.path !== '/login') {
                next({
                    path: '/login',
                    replace: true
                })
            } else {
                next(false)
            }
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})

router.onError((err) => {
    Message.error(err.message)
})

export default router
